﻿using System;
using System.Data;
//using System.Windows.Forms;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Model;

public partial class Assemble_AssembleDetailAdd : System.Web.UI.Page
{
    private AssembleDetail amd;
    private AssembleDetails amds;
    private DataRow dr;
    private DataTable amddt
    {
        get
        {
            return (DataTable)ViewState["amddt"];
        }
        set
        {
            ViewState["amddt"] = value;
        }
    }

    public Assemble_AssembleDetailAdd()
    {
        amd = new AssembleDetail();
        amds = new AssembleDetails();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            amddt = new DataTable();
            amddt.Columns.Add(new DataColumn("BatchID", Type.GetType("System.String")));
            amddt.Columns.Add(new DataColumn("StuffTypeID", Type.GetType("System.String")));
            amddt.Columns.Add(new DataColumn("Remark", Type.GetType("System.String")));
            amddt.Columns.Add(new DataColumn("Amount", Type.GetType("System.Int32")));
        }
        //Bindamd();
        //if (User.Identity.Name == "10307")
        //{
        //    this.Button3.Visible = true;
        //}
    }

    protected void TextBox2_TextChanged(object sender, EventArgs e)
    {
        string batchid = this.TextBox2.Text.Trim();
        int amount;
        if (!int.TryParse(this.TextBox7.Text.Trim(), out amount) || amount <= 0)
        {
            string str = "批次对应数量不是正整数！请检查";
            ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');</script>", false);
            return;
        }
        try
        {
            this.TextBox3.Text = batchid.Substring(batchid.Length - 17, 10);
        }
        catch
        {
            string str = "批次序列号不能少于19位！请检查";
            ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');</script>", false);
            return;
        }

        Page.Validate("VGroup2");
        if (Page.IsValid)
        {
            dr = amddt.NewRow();
            dr["BatchID"] = this.TextBox2.Text.Trim();
            dr["StuffTypeID"] = this.TextBox3.Text.Trim();
            dr["Remark"] = this.TextBox6.Text.Trim();
            dr["Amount"] = amount;
            if (amddt.Select("BatchID = '" + this.TextBox2.Text.Trim() + "'").Length == 0)
            {
                //替换同一StuffTypeID的物料信息
                if (amddt.Select("StuffTypeID = '" + this.TextBox3.Text.Trim() + "'").Length > 0)
                    amddt.Select("StuffTypeID = '" + this.TextBox3.Text.Trim() + "'")[0].Delete();
                amddt.Rows.InsertAt(dr, 0);
                Bindamd();
                this.TextBox7.Text = "";
                this.TextBox2.Text = "";
                this.TextBox3.Text = "";
                this.TextBox6.Text = "";
                this.TextBox7.Focus();
            }
            else
            {
                string str = "已经在列表中";
                ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');</script>", false);
            }
        }
    }

    protected void TextBox6_TextChanged(object sender, EventArgs e)
    {
        this.TextBox2.Focus();
    }

    protected void Bindamd()
    {
        this.GridView1.DataSource = amddt;
        this.GridView1.DataBind();
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            {
                ((LinkButton)e.Row.Cells[4].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除!')");
            }
        }
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        amddt.Select("BatchID = '" + GridView1.Rows[e.RowIndex].Cells[0].Text + "'")[0].Delete();
        Bindamd();
    }

    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
        Page.Validate("VGroup1");
        if (Page.IsValid)
        {
            if (amddt.Rows.Count < 1)
            {
                string str = "请先添加关键物料信息!";
                ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');</script>", false);
                return;
            }
            else
            {
                if (amddt.Select("Amount = 0").Length > 0)
                {
                    string str = "批次物料：" + amddt.Select("Amount = 0")[0]["BatchID"].ToString() + "剩余数量不足，请检查！";
                    ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');</script>", false);
                    return;
                }
                else
                {
                    string productSN = this.TextBox1.Text.Trim();
                    if (amd.GetAssembleDetailbySN(productSN).Count > 0)
                    {
                        ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>GetConfirm();</script>", false);
                    }
                    //此方法在asp.net中只作服务器端调试用，在客户端浏览器中没有效果
                    //MessageBox.Show("此产品序列号已经录入过物料装配信息，" + "\r\n" + "是否要继续!", "重号提示",MessageBoxButtons.OKCancel, 
                    //MessageBoxIcon.Question, MessageBoxDefaultButton.Button1,MessageBoxOptions.DefaultDesktopOnly) == DialogResult.Cancel) return;
                    else
                    {
                        AssembleDetail_BuildandAdd();
                    }
                }
            }
        }
    }

    /// <summary>
    /// 序列号已经录入过且提示后，用户选择继续录入时的处理
    /// 上述整个功能的代码执行流程为：用户点击btnTransfer按钮并引发该按钮的Click事件-->执行完btnTransfer_Click事件处理函数中所有服务端代码
    /// -->执行GetConfirm客户端脚本函数-->通过__doPostBack函数引发LinkButton1按钮回传
    /// -->执行LinkButton1按钮的Click事件处理函数-->根据confirm返回值（保存在confirmReturnValue控件中）继续后台程序逻辑。
    /// </summary>
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        if (confirmReturnValue.Value == "True")
        {
            AssembleDetail_BuildandAdd();
        }
        else
        {
            return;
        }
    }

    private void AssembleDetail_BuildandAdd()
    {
        string productSN = this.TextBox1.Text.Trim();
        string productTypeID = this.TextBox4.Text.Trim();
        string mOID = this.TextBox5.Text.Trim();
        MOBuildandAdd(productTypeID, mOID);

        if (CommHelper.IsValidSN_forDataAcquisition(productSN))//判断序列号是否合法可录入序列号
        {
            productSN = CommHelper.GetProductSN(productSN);//如果是关联过的成品序列号，则转换为相应的腔体序列号
            HouseBuildandAdd(mOID, productSN);

            string ip = IPGet.getIp();
            DateTime dt = DateTime.Now;
            AssembleDetailInfo adi = new AssembleDetailInfo(productSN, dt, User.Identity.Name, ip, mOID);
            if (amd.AssembleDetailItems_Insert(adi, amddt))
            {
                //详细物料数据重新加载
                GetOrRefreshDetails();
                string str = " 提交成功!";
                ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');</script>", false);
                this.TextBox1.Text = "";
                this.TextBox1.Focus();
            }
            else
            {
                string str = "提交失败，请联系相关人员!";
                ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');</script>", false);
            }
        }
        else
        {
            string str = "序列号不符合腔体序列号编码规则，或不是关联过的成品序列号，请检查!";
            ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "<script>alert('" + str + "');</script>", false);
        }

    }

    protected void MOBuildandAdd(string productTypeID, string mOID)
    {
        MOInfo moi = new MOInfo(mOID, productTypeID);
        MO m = new MO();
        m.Insert(moi);
    }

    protected void HouseBuildandAdd(string mOID, string productSN)
    {
        HouseInfo hi = new HouseInfo(productSN, mOID);
        House h = new House();
        h.Insert(hi);
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        GetOrRefreshDetails();
    }

    protected void GetOrRefreshDetails()
    {
        string ip = IPGet.getIp();
        string mo = this.TextBox5.Text.Trim();
        IList<AssembleDetailsInfo> list = amds.GetAssembleDetailsbyIPMO(mo, ip);
        Appendtoamddt(list);
    }

    protected void Appendtoamddt(IList<AssembleDetailsInfo> list)
    {
        amddt.Clear();
        foreach (AssembleDetailsInfo amdsi in list)
        {
            dr = amddt.NewRow();
            dr["BatchID"] = amdsi.BatchID;
            dr["StuffTypeID"] = amdsi.StuffTypeID;
            dr["Remark"] = amdsi.Remark;
            dr["Amount"] = amdsi.Amount;
            amddt.Rows.Add(dr);
        }
        Bindamd();
    }

    protected void TextBox4_TextChanged(object sender, EventArgs e)
    {
        this.TextBox5.Focus();
    }

    protected void TextBox5_TextChanged(object sender, EventArgs e)
    {
        this.Button3.Focus();
    }
}
